package com.online.action;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * Spring MVC 异常信息拦截。打印详细异常信息，方便排查异常。
 * 
 * @author trunks
 *
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

	Log log = LogFactory.getLog(ExceptionHandler.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		StringBuilder sb = new StringBuilder("\n请求参数：{");
		Map<String, Object> params = request.getParameterMap();
		Enumeration<String> headers = request.getHeaderNames();

		for (String param : params.keySet()) {
			sb.append(param).append(":").append(request.getParameter(param))
					.append(",");
		}
		sb.append("}");
		sb.append("\nIP:" + request.getRemoteAddr());
		sb.append("\n请求URL：").append(request.getRequestURL());
		sb.append("\n头信息：");
		while (headers.hasMoreElements()) {
			String header = headers.nextElement();
			sb.append("\n\t").append(header).append(":")
					.append(request.getHeader(header));
		}
		
		if (handler != null) {
			HandlerMethod hm = (HandlerMethod) handler;
			sb.append("\n异常方法：").append(hm.getMethod().toGenericString());
		}
		sb.append("\n异常类型：").append(ex.getClass());
		sb.append("\n异常信息：").append(ex.getMessage());
		log.error(sb.toString());
		return null;
	}

}
